import { createStore } from 'vuex'
import { KEYS, set, get } from '@/utils/Storage'
import httpApi from '@/http'
import router from "@/router";
import { ElMessage } from 'element-plus'
export default createStore({
  state: {
    // user: get(KEYS.USER_INFO),
    user: '张三', // 这里是模拟的，实际应该从后端获取
    token: get(KEYS.TOKEN),
    id: get(KEYS.USER_ID),
    role: 'admin',
  },
  getters: {
  },
  mutations: {
    // 声明方法修改state中的值
    updateUser(state, payload) {
      state.user = payload
    },
    saveToken(state, token) {
      state.token = token
    },
    updateMyState(state, newValue) {
      state.user = newValue;
      state.token = newValue;
      state.id = newValue;
    }
  },
  actions: {
    /**
    * 执行异步的登录业务 ，登录成功后将用户对象存入state（调用mutations）
    * @param  Store vuex自定传入  Store对象
    * @param  params 用户传入的参数 {account：xx,password：xx}
    */
    loginto(store, params) {
      if (!params) {
        return
      } else {
        httpApi.loginApi.login(params).then(res => {
          console.log(res, 'res')
          if (res.data.code == 200) {
            console.log(res.data.data);
            store.commit('updateUser', res.data.data.admin)
            store.commit('saveToken', res.data.token)
            set(KEYS.USER_INFO, res.data.data[0].admin)
            set(KEYS.TOKEN, res.data.token)
            set(KEYS.USER_ID, res.data.data[0].admin)
            router.push('/')
            window.location.reload()
          } else {
            alert('账号或密码错误')
          }
        }).catch(err => {
          console.log(err, 'err');
          ElMessage.error('登录失败')
        })
      }

    }
  },
  modules: {
  }
})
